package com.ruoyi.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.exception.user.UserPasswordNotMatchException;
import com.ruoyi.framework.web.service.TokenService;
import com.ruoyi.framework.web.service.UserDetailsServiceImpl;
import com.ruoyi.service.UserService;
import com.ruoyi.system.domain.*;
import com.ruoyi.system.mapper.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.Objects;

@Service
public class UserServiceImpl implements UserService {
	@Autowired
	TokenService tokenService;
	@Autowired
	private AuthenticationManager authenticationManager;
	
	@Autowired
	private GuiZhangMapper guiZhangMapper;
	
	@Autowired
	private XingZhengGuiFanMapper xingZhengGuiFanMapper;
	
	@Autowired
	private GongKaiZhiLanMapper gongKaiZhiLanMapper;
	
	@Autowired
	private GongKaiZhiDuMapper gongKaiZhiDuMapper;
	
	@Autowired
	private XingZhengGongKaiMapper xingZhengGongKaiMapper;
	
	@Autowired
	private FApplysMapper fApplysMapper;
	@Autowired
	private FAreasMapper fAreasMapper;
	@Autowired
	private FDepartmentsMapper fDepartmentsMapper;
	@Autowired
	private FUserMapper fUserMapper;
	@Autowired
	private PasswordEncoder passwordEncoder;
	
	private static final Logger log = LoggerFactory.getLogger(UserDetailsServiceImpl.class);
	
	@Override
	public AjaxResult login(Map<String, String> params) {
		// 账号密码授权
		UsernamePasswordAuthenticationToken usernamePasswordAuthenticationToken = new UsernamePasswordAuthenticationToken(params.get("username"), params.get("password"));
		// 认证环节
		Authentication authenticate = null;
		try {
			authenticate = authenticationManager.authenticate(usernamePasswordAuthenticationToken);
			if (Objects.isNull(authenticate)) {
				throw new RuntimeException("用户名或密码错误!!!");
			}
		} catch (Exception e) {
			if (e instanceof BadCredentialsException) {
				throw new UserPasswordNotMatchException();
			} else {
				throw new ServiceException(e.getMessage());
			}
		}
		// 创建token
		FrontLoginUser frontLoginUser = (FrontLoginUser) authenticate.getPrincipal();
		Users frontUsers = frontLoginUser.getFrontUsers();
		frontUsers.setToken(tokenService.createToken(frontLoginUser));
		return AjaxResult.success("操作成功", frontUsers);
	}
	
	@Override
	public AjaxResult userInfo() {
		FrontLoginUser principal = (FrontLoginUser) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
		Users users = fUserMapper.selectById(principal.getFrontUsers().getId());
		return AjaxResult.success(users);
	}
	
	@Override
	public AjaxResult register(Users users) {
		// 检查用户名
		QueryWrapper<Users> fUsersQueryWrapper = new QueryWrapper<>();
		fUsersQueryWrapper.eq("username", users.getUsername());
		fUsersQueryWrapper.or();
		fUsersQueryWrapper.eq("card_id", users.getCardId());
		List<Users> users1 = fUserMapper.selectList(fUsersQueryWrapper);
		if (!users1.isEmpty()) {
			return AjaxResult.error("重复注册");
			
		}
		users.setPassword(passwordEncoder.encode(users.getPassword()));
		int insert = fUserMapper.insert(users);
		return AjaxResult.success("success", users);
	}
	
	
	@Override
	public AjaxResult guizhangList(Map<String, Object> params) {
		// 构造查询条件
		QueryWrapper<GuiZhang> objectQueryWrapper = new QueryWrapper<>();
		if (params.containsKey("title") && !Objects.isNull(params.containsKey("title"))) {
			objectQueryWrapper.like("title", String.valueOf(params.get("title")));
		}
		// 分页
		Page<GuiZhang> objectPage = new Page<>();
		int pageNum = Integer.parseInt(String.valueOf(params.getOrDefault("pageNum", 1)));
		int pageSize = Integer.parseInt(String.valueOf(params.getOrDefault("pageSize", 5)));
		objectPage.setCurrent(pageNum);
		objectPage.setSize(pageSize);
		Page<GuiZhang> guiZhangPage = guiZhangMapper.selectPage(objectPage, objectQueryWrapper);
		return AjaxResult.success(guiZhangPage);
	}
	
	@Override
	public AjaxResult guizhangDetail(Integer id) {
		QueryWrapper<GuiZhang> objectQueryWrapper = new QueryWrapper<>();
		objectQueryWrapper.eq("id", id);
		GuiZhang guiZhang = guiZhangMapper.selectOne(objectQueryWrapper);
		return AjaxResult.success(guiZhang);
	}
	
	@Override
	public AjaxResult guizhangDelete(Integer id) {
		QueryWrapper<GuiZhang> objectQueryWrapper = new QueryWrapper<>();
		objectQueryWrapper.eq("id", id);
		int delete = guiZhangMapper.delete(objectQueryWrapper);
		return AjaxResult.success(delete);
	}
	
	@Override
	public AjaxResult xing_zheng_gui_fan_list(Map<String, Object> params) {
		// 构造查询条件
		QueryWrapper<FXingZhengGuiFan> objectQueryWrapper = new QueryWrapper<>();
		// 标题
		if (params.containsKey("title") && !Objects.isNull(params.get("title"))) {
			objectQueryWrapper.like("title", String.valueOf(params.get("title")));
		}
		// 正文
		if (params.containsKey("content") && !Objects.isNull(params.get("content"))) {
			objectQueryWrapper.like("content", String.valueOf(params.get("content")));
		}
		// 文号
		if (params.containsKey("article_no") && !Objects.isNull(params.get("article_no"))) {
			objectQueryWrapper.like("article_no", String.valueOf(params.get("article_no")));
		}
		// 查询全部
		if (params.containsKey("all") && !Objects.isNull(params.get("all"))) {
			objectQueryWrapper.like("article_no", String.valueOf(params.get("all"))).or().like("content", String.valueOf(params.get("all"))).or().like("title", String.valueOf(params.get("all")));
		}
		// 分页
		Page<FXingZhengGuiFan> objectPage = new Page<>();
		int pageNum = Integer.parseInt(String.valueOf(params.getOrDefault("pageNum", 1)));
		int pageSize = Integer.parseInt(String.valueOf(params.getOrDefault("pageSize", 5)));
		objectPage.setCurrent(pageNum);
		objectPage.setSize(pageSize);
		Page<FXingZhengGuiFan> xingZhengGuiFanPage = xingZhengGuiFanMapper.selectPage(objectPage, objectQueryWrapper);
		return AjaxResult.success(xingZhengGuiFanPage);
	}
	
	@Override
	public AjaxResult xing_zheng_gui_fan_detail(Integer id) {
		QueryWrapper<FXingZhengGuiFan> objectQueryWrapper = new QueryWrapper<>();
		objectQueryWrapper.eq("id", id);
		FXingZhengGuiFan fXingZhengGuiFan = xingZhengGuiFanMapper.selectOne(objectQueryWrapper);
		return AjaxResult.success(fXingZhengGuiFan);
	}
	
	@Override
	public AjaxResult xing_zheng_gui_fan_delete(Integer id) {
		QueryWrapper<FXingZhengGuiFan> objectQueryWrapper = new QueryWrapper<>();
		objectQueryWrapper.eq("id", id);
		int delete = xingZhengGuiFanMapper.delete(objectQueryWrapper);
		return AjaxResult.success(delete);
	}
	
	@Override
	public AjaxResult gong_kai_zhi_lan_list(Map<String, Object> params) {
		// 构造查询条件
		QueryWrapper<FGongKaiZhiLan> objectQueryWrapper = new QueryWrapper<>();
		if (params.containsKey("title") && !Objects.isNull(params.get("title"))) {
			objectQueryWrapper.like("title", String.valueOf(params.get("title")));
		}
		// 分页
		Page<FGongKaiZhiLan> objectPage = new Page<>();
		int pageNum = Integer.parseInt(String.valueOf(params.getOrDefault("pageNum", 1)));
		int pageSize = Integer.parseInt(String.valueOf(params.getOrDefault("pageSize", 5)));
		objectPage.setCurrent(pageNum);
		objectPage.setSize(pageSize);
		Page<FGongKaiZhiLan> guiZhangPage = gongKaiZhiLanMapper.selectPage(objectPage, objectQueryWrapper);
		return AjaxResult.success(guiZhangPage);
	}
	
	@Override
	public AjaxResult gong_kai_zhi_du_list(Map<String, Object> params) {
		// 构造查询条件
		QueryWrapper<FGongKaiZhiDu> objectQueryWrapper = new QueryWrapper<>();
		// 标题
		if (params.containsKey("title") && !Objects.isNull(params.get("title"))) {
			objectQueryWrapper.like("title", String.valueOf(params.get("title")));
		}
		// 正文
		if (params.containsKey("content") && !Objects.isNull(params.get("content"))) {
			objectQueryWrapper.like("content", String.valueOf(params.get("content")));
		}
		// 文号
		if (params.containsKey("article_no") && !Objects.isNull(params.get("article_no"))) {
			objectQueryWrapper.like("article_no", String.valueOf(params.get("article_no")));
		}
		// 分页
		Page<FGongKaiZhiDu> objectPage = new Page<>();
		int pageNum = Integer.parseInt(String.valueOf(params.getOrDefault("pageNum", 1)));
		int pageSize = Integer.parseInt(String.valueOf(params.getOrDefault("pageSize", 5)));
		objectPage.setCurrent(pageNum);
		objectPage.setSize(pageSize);
		Page<FGongKaiZhiDu> gongKaiZhiDuPage = gongKaiZhiDuMapper.selectPage(objectPage, objectQueryWrapper);
		return AjaxResult.success(gongKaiZhiDuPage);
	}
	
	@Override
	public AjaxResult gong_kai_zhi_du_detail(Integer id) {
		QueryWrapper<FGongKaiZhiDu> objectQueryWrapper = new QueryWrapper<>();
		objectQueryWrapper.eq("id", id);
		FGongKaiZhiDu gongKaiZhiDu = gongKaiZhiDuMapper.selectOne(objectQueryWrapper);
		return AjaxResult.success(gongKaiZhiDu);
	}
	
	@Override
	public AjaxResult gong_kai_zhi_du_delete(Integer id) {
		QueryWrapper<FGongKaiZhiDu> objectQueryWrapper = new QueryWrapper<>();
		objectQueryWrapper.eq("id", id);
		int delete = gongKaiZhiDuMapper.delete(objectQueryWrapper);
		return AjaxResult.success(delete);
	}
	
	@Override
	public AjaxResult xing_zheng_gong_kai_list(Map<String, Object> params) {
		// 构造查询条件
		QueryWrapper<FXingZhengGongKai> objectQueryWrapper = new QueryWrapper<>();
		
		switch (String.valueOf(params.get("searchType"))) {
			case "biao_ti":
				if (!Objects.isNull(params.get("keyword"))) {
					objectQueryWrapper.like("title", String.valueOf(params.get("keyword")));
				}
				break;
			case "zheng_wen":
				if (!Objects.isNull(params.get("keyword"))) {
					objectQueryWrapper.like("content", String.valueOf(params.get("keyword")));
				}
				break;
			case "wen_hao":
				if (!Objects.isNull(params.get("keyword"))) {
					objectQueryWrapper.like("article_no", String.valueOf(params.get("keyword")));
				}
				break;
			case "ji_gou":
				if (!Objects.isNull(params.get("keyword"))) {
					objectQueryWrapper.like("department", String.valueOf(params.get("keyword")));
				}
				break;
			case "mo_kuai":
				if (!Objects.isNull(params.get("keyword"))) {
					objectQueryWrapper.like("type", String.valueOf(params.get("keyword")));
				}
				break;
			default:
				// 类型
				if (params.containsKey("type") && !Objects.isNull(params.get("type"))) {
					objectQueryWrapper.eq("type", String.valueOf(params.get("type")).trim());
				}
				break;
		}
		// 分页
		Page<FXingZhengGongKai> objectPage = new Page<>();
		int pageNum = Integer.parseInt(String.valueOf(params.getOrDefault("pageNum", 1)));
		int pageSize = Integer.parseInt(String.valueOf(params.getOrDefault("pageSize", 5)));
		objectPage.setCurrent(pageNum);
		objectPage.setSize(pageSize);
		Page<FXingZhengGongKai> gongKaiZhiDuPage = xingZhengGongKaiMapper.selectPage(objectPage, objectQueryWrapper);
		return AjaxResult.success(gongKaiZhiDuPage);
	}
	
	@Override
	public AjaxResult xing_zheng_gong_kai_detail(Integer id) {
		QueryWrapper<FXingZhengGongKai> objectQueryWrapper = new QueryWrapper<>();
		objectQueryWrapper.eq("id", id);
		FXingZhengGongKai xingZhengGongKai = xingZhengGongKaiMapper.selectOne(objectQueryWrapper);
		return AjaxResult.success(xingZhengGongKai);
	}
	
	@Override
	public AjaxResult xing_zheng_gong_kai_delete(Integer id) {
		QueryWrapper<FXingZhengGongKai> objectQueryWrapper = new QueryWrapper<>();
		objectQueryWrapper.eq("id", id);
		int delete = xingZhengGongKaiMapper.delete(objectQueryWrapper);
		return AjaxResult.success(delete);
	}
	
	@Override
	public AjaxResult applyCreate(FApplys fApplys) {
		fApplysMapper.insert(fApplys);
		return AjaxResult.success("success", fApplys);
	}
	
	@Override
	public AjaxResult applyList(Map<String, Object> params) {
		// 构造查询条件
		QueryWrapper<FApplys> objectQueryWrapper = new QueryWrapper<>();
		// 用户
		if (params.containsKey("user_id") && !StringUtils.isBlank(String.valueOf(params.get("user_id")))) {
			objectQueryWrapper.eq("user_id", String.valueOf(params.get("user_id")).trim());
		}
		// 类型
		if (params.containsKey("status") && !StringUtils.isBlank(String.valueOf(params.get("status")))) {
			objectQueryWrapper.eq("status", String.valueOf(params.get("status")).trim());
		}
		// 时间
		if (!StringUtils.isBlank(String.valueOf(params.get("startTime"))) && !StringUtils.isBlank(String.valueOf(params.get("endTime")))) {
			objectQueryWrapper.between("created_time", String.valueOf(params.get("startTime")).trim(), String.valueOf(params.get("endTime")).trim());
		}
		// 区域
		if (params.containsKey("areaId") && !StringUtils.isBlank(String.valueOf(params.get("areaId")))) {
			objectQueryWrapper.eq("area_id", String.valueOf(params.get("areaId")).trim());
		}
		// 部门
		if (params.containsKey("departmentId") && !StringUtils.isBlank(String.valueOf(params.get("departmentId")))) {
			objectQueryWrapper.eq("department_id", String.valueOf(params.get("departmentId")).trim());
		}
		
		// 分页
		Page<FApplys> objectPage = new Page<>();
		int pageNum = Integer.parseInt(String.valueOf(params.getOrDefault("pageNum", 1)));
		int pageSize = Integer.parseInt(String.valueOf(params.getOrDefault("pageSize", 5)));
		objectPage.setCurrent(pageNum);
		objectPage.setSize(pageSize);
		Page<FApplys> gongKaiZhiDuPage = fApplysMapper.selectPage(objectPage, objectQueryWrapper);
		return AjaxResult.success(gongKaiZhiDuPage);
	}
	
	@Override
	public AjaxResult applyUpdate(Map<String, Object> params) {
		FApplys fApplys = new FApplys();
		fApplys.setId(Long.valueOf(String.valueOf(params.get("id"))));
		// fApplys.setOperatorUserId(Long.valueOf(String.valueOf(params.get("operatorUserId"))));
		fApplys.setStatus(String.valueOf(params.get("status")));
		// fApplys.setRemark(String.valueOf(params.get("remark")));
		// fApplys.setConfirmFile(String.valueOf(params.get("confirmFile")));
		int i = fApplysMapper.updateById(fApplys);
		return AjaxResult.success("操作成功", i);
	}
	
	@Override
	public AjaxResult areaList() {
		QueryWrapper<FAreas> fAreasQueryWrapper = new QueryWrapper<>();
		List<FAreas> fAreas = fAreasMapper.selectList(fAreasQueryWrapper);
		fAreas.forEach(fAreas1 -> {
			QueryWrapper<FDepartments> fDepartmentsQueryWrapper = new QueryWrapper<>();
			fDepartmentsQueryWrapper.eq("area_id", fAreas1.getId());
			List<FDepartments> fDepartments = fDepartmentsMapper.selectList(fDepartmentsQueryWrapper);
			fAreas1.setFDepartmentsList(fDepartments);
		});
		return AjaxResult.success(fAreas);
	}
	
}
